package fn;

public class Multiply extends Function {

	private Function[] child;

	private Multiply(Function f0, Function f1) {
		child = new Function[] {
				f0, f1
		};
	}

	public static Function create(Function f0, Function f1) {
		// rule 1 : multiplying by 0
		if (f0 instanceof Constant && ((Constant) f0).value() == 0)
			return f0;
		if (f1 instanceof Constant && ((Constant) f1).value() == 0)
			return f1;
		// rule 2 : multiplying by 1
		if (f0 instanceof Constant && ((Constant) f0).value() == 1)
			return f1;
		if (f1 instanceof Constant && ((Constant) f1).value() == 1)
			return f0;
		return new Multiply(f0, f1);
	}

	@Override
	protected Function[] child() {
		return child;
	}

	@Override
	public double evaluate(double sub) {
		return child[0].evaluate(sub) * child[1].evaluate(sub);
	}

	@Override
	public String prefix() {
		return "";
	}

	@Override
	public String infix() {
		return " \\cdot ";
	}

	@Override
	public String postfix() {
		return "";
	}

	@Override
	protected int precedence() {
		return 2;
	}

	@Override
	protected boolean withPar() {
		return true;
	}

	@Override
	public Function derivative() {
		Function out = Add.create(create(child[0].derivative(), child[1]), create(child[1].derivative(), child[0]));
		return out;
	}
}
